3
3
.
.
1
1
B
B
a
a
s
s
i
i
c
c
S
S
y
y
n
n
t
t
a
a
x
x
C
C
o
o
m
m
m
m
e
e
n
n
t
t
s
s
Comments
//Single line comment.
/* Multi line
comment. */
P
P
r
r
i
i
n
n
t
t
&
&
D
D
u
u
m
m
p
p
print() doesn't show class details.
dump() works the same on both class and struct.
Print & Dump
//DECLARE VARIABLES.
var name = "John"
var age = 20
//DISPLAY VARIABLES.
print("Hello " + name) //Hello John (Concatenation)
print("\(name) is \(age) years old") //John is 20 years old
dump ("\(name) is \(age) years old") //John is 20 years old
Print vs Dump
STRUCT
CLASS
print()
Person(name: "John", age: 20)
SwiftPlayground.Person
dump()
SwiftPlayground.Person
- name: "John"
- age: 20
SwiftPlayground.Person #0
- name: "John"
- age: 20
S
S
t
t
a
a
t
t
e
e
m
m
e
e
n
n
t
t
s
s
-
-
C
C
o
o
n
n
d
d
i
i
t
t
i
i
o
o
n
n
a
a
l
l
if (evaluates over different Variables/Conditions)
if (name == "John") { print("Name is John") }
else if (name == "Bill") { print("Name is Bill") }
else if (name == "Lucy") { print("Name is Lucy") }
else { print("No match") }
switch (evaluates over the same Variable/Condition)
switch (name) {
case "John":
print("Name is John") //Only selected case is executed.
case "Bill":
print("Name is Bill") //There can be multiple commands inside each case
print("Found Bill")
default:
print("No match")
}
CONDITION ? TRUE : FALSE (simplified if...else)
//CONDITION ? TRUE : FALSE
name == "John" ? print("Name is John") : print("Name is NOT John") //All in a single line
S
S
t
t
a
a
t
t
e
e
m
m
e
e
n
n
t
t
s
s
-
-
L
L
o
o
o
o
p
p
for
for i in 1...5 { print(i) } //ITERATE THROUGH SEQUENCE: 1 2 3 4 5
for person in ["John", "Bill", "Lucy"] { print(person) } //ITERATE THROUGH ARRAY.
while
var i = 0
while(i < 5) {
i = i + 1
print(i)
}
repeat
var i = 0
repeat {
i = i + 1
print(i)
} while(i < 5)
S
S
t
t
a
a
t
t
e
e
m
m
e
e
n
n
t
t
s
s
-
-
J
J
u
u
m
m
p
p
Break
for i in 1...5 {
if(i==3) { break } //Break from Loop.
print(i) //1, 2
}
Continue
for i in 1...5 {
if(i==3) { continue } //Continue with next iteration of the loop (skips subsequent lines)
print(i) //1, 2, 4, 5
}
Return
//DECLARE FUNCTION.
func greet () -> (String) {
return("Hello") //Return string.
print("Never executed") //Skipped line.
}
//CALL FUNCTION.
var result = greet() //Store function return value into variable result.
print(result)